package io.github.lee.core.vm

import android.app.Application
import androidx.annotation.IntRange
import com.chad.library.adapter4.BaseQuickAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.MutableSharedFlow

abstract class BaseRefreshViewModel<T : Any>(application: Application) :
    BaseViewModel(application) {
    protected var currentPage = 1

    val adapter: BaseQuickAdapter<T, *> by lazy { onCreateAdapter() }

    private val checkFullPage = MutableSharedFlow<Boolean>()
    fun collectCheckFullPage(collector: FlowCollector<Boolean>) {
        launch(Dispatchers.IO) {
            checkFullPage.collect(collector)
        }
    }

    protected abstract fun onCreateAdapter(): BaseQuickAdapter<T, *>

    open fun onRefreshOrLoadMore(isRefresh: Boolean) {
    }

    //===Desc:======================================================================================

    fun submitList(list: List<T>?) {
        launch(Dispatchers.Main) {
            adapter.submitList(list)
            checkFullPage.emit(true)
        }
    }

    fun addData(data: T, @IntRange(from = 0) position: Int? = null) {
        if (null == position) {
            adapter.add(data)
        } else {
            adapter.add(position, data)
        }
    }

    fun addAll(list: Collection<T>, @IntRange(from = 0) position: Int? = null) {
        if (null == position) {
            adapter.addAll(list)
        } else {
            adapter.addAll(position, list)
        }
    }

    fun remove(data: T) {
        adapter.remove(data)
    }

    fun removeAt(@IntRange(from = 0) position: Int) {
        adapter.removeAt(position)
    }

    fun getItem(position: Int): T? =
        adapter.getItem(position)

}